<?php
echo('title Video Encode System [Build:20180312T1]');
echo "Video Encode System\n";
echo "===================\n";
echo "Build By haha_Dashen\n";
echo "Base on PackPHPFrame\n";
echo "Build:20180312T1\n";
echo "===================\n";
echo "Loading Function Database......";
include("include/function.php");
include ("config/config.php");
//Color Text Support
Col_echo("[Successful]\n",'green');
Col_echo("Connecting to Redis......",'light_blue');
$redis=Redis_Link();
$redis->set('Main_Start','OK');
$redis->flushDB();
Col_echo("[Successful]\n",'green');
Col_echo("Connecting to Mysql......",'light_blue');
$db_link=DB_Link();
Col_echo("[Successful]\n",'green');
Col_echo("[Main] Dump Setting\n","brown");
$encode_bitrate_video=Get_Config('encode_bitrate_video');
$encode_bitrate_audio=Get_Config('encode_bitrate_audio');
$encode_ts_time=Get_Config('encode_ts_time');
$encode_ts_frame=Get_Config('encode_ts_frame');
$worker_thread=Get_Config('worker_thread');
if ($dual_socket_support==1){
    Col_echo("[Main] Dual Socket Support Enable!\n","brown");
}
//Pull Up Multithread

for ($i=1;$i<=$worker_thread;$i++){
    pclose(popen('start php\php.exe -c php\php.ini worker.php','r'));
    Col_echo("[MultiThread] Pulling up Thread ".$i."#\n",'light_blue');
    sleep(1);
}
Col_echo("[MultiThread] Successful Pull All Thread Up\n",'green');
$redis->set('Main_Start',"OK");
start:
Col_echo("[MultiThread] Time:".date("Y-m-d H:i:s")."\n","brown");
//Dynamic Load Config
$encode_bitrate_video=Get_Config('encode_bitrate_video');
$encode_bitrate_audio=Get_Config('encode_bitrate_audio');
$encode_ts_time=Get_Config('encode_ts_time');
$encode_ts_frame=Get_Config('encode_ts_frame');
$worker_thread=Get_Config('worker_thread');
//
$worker_free=0;
$worker_busy=0;
$worker_down=0;
$start_sign=$redis->get('Main_Start');
for ($i=1;$i<=$worker_thread;$i++){
    $status=$redis->get('Worker_Status_'.$i);

    if (empty($status) and $start_sign == "OK"){
        $worker_down++;
        Col_echo("[MultiThread] Worker ".$i."# Down! Let it Back Up!!!\n",'red');
        pclose(popen('start php\php.exe -c php\php.ini worker.php','r'));
        sleep(1);
    }elseif ($status=="1"){
        $worker_free++;
    }elseif ($status=="2"){
        $worker_busy++;
    }
    $status=0;
}
Col_echo("[MultiThread] Free:".$worker_free." Busy:".$worker_busy." Down:".$worker_down."\n",'white');
//

Col_echo("[Encode Status]:".$start_sign."\n",'white');
if ($start_sign == 'OK'){
    Col_echo("[File] Searching Encode File\n",'cyan');
    $file=getFile("upload");
    if (empty($file[0])){
        Col_echo("[File] No File Find\n",'cyan');
    }else{
        for ($num=0;!empty($file[$num]);$num++){
            $ext=pathinfo($file[$num],PATHINFO_EXTENSION);
            if ($ext == "ass" or $ext == "srt"){
                continue;
            }
            //MD5
            $md5=md5_file('upload/'.$file[$num]);
            $already=mysqli_fetch_array(mysqli_query($db_link,"SELECT * FROM video_list WHERE md5 = '".$md5."'"));
            if (!empty($already['ID'])){
                Col_echo("[File] MD5 Matched \n",'green');
               // mysqli_query($db_link,"INSERT INTO `video_list` (`ID`, `filename`, `random`, `day`, `time`, `status`, `md5`, `sid`, `shareid`, `m_size`, `m_time`) VALUES (NULL, '".$file[$num]."', '".$already['random']."', '".$already['day']."', '".time()."', '2', '".$md5."', '".$already['sid']."', '".$already['shareid']."', '".$already['m_size']."', '".$already['m_time']."')");
                unlink('upload/'.$file[$num]);
            }else{
                $today=date("Ymd",time());
                $random=Random_String(8);
                $sid=Random_String(24);
                $shareid=Random_String(16);
                $size=0;
                $time=0;
                $old="upload/".$file[$num];
                $new="encoding/".$file[$num];
                if (rename($old,$new)) {
                    mysqli_query($db_link, "INSERT INTO `video_list` (`ID`, `filename`, `random`, `day`, `time`, `status`, `md5`, `sid`, `shareid`, `m_size`, `m_time`) VALUES (NULL, '" . $file[$num] . "', '" . $random . "', '" . $today . "', '" . time() . "', '0', '" . $md5 . "', '" . $sid . "', '" . $shareid . "', $size, $time)");
                    Col_echo("[File] Find 1 Encode File\n", 'light_blue');
                }
            }
        }
    }
    //$redis->del('Main_Start');
}
//
$result_waiting=mysqli_query($db_link,"SELECT * FROM video_list WHERE status = '0'");
Col_echo("[TaskManager] Start Push Task\n",'purple');
$waiting=0;
while ($row_waiting = mysqli_fetch_array($result_waiting)){
    $find=0;
    for ($i=1;$i<=$worker_thread&&$find==0;$i++){
        $status=$redis->get('Worker_Status_'.$i);
        $already_work=$redis->get('Worker_Info_'.$i);
        if ($status==1&&empty($already_work)){
            Col_echo("[TaskManager] Push Task To ".$i."#\n",'light_purple');
            $redis->set('Worker_Status_'.$i,'2');
            $data['ID']=$row_waiting['ID'];
            $redis->set('Work_Info_'.$i,json_encode($data));
            $find=1;
        }
    }
    if ($find==0){
        $waiting++;
    }
}
Col_echo("[TaskManager] ".$waiting." Task Waiting\n",'purple');
sleep(10);
goto start;